package com.liu.tcpDemo.Client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Connect {
    public static boolean socketState = false;
    public static void getConnect(String host ,int port){
        try {
            Socket socket=new Socket(host,port);
            socketState=true;
            if (Connect.socketState){
//                注意！向服务端发送消息的时候，服务端只会接收一个oos对象,如果oos对象不同就会报错，心跳包要和发送的消息用同一个oos对象
                ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                new Thread(new ClientListen(socket)).start();
                new Thread(new ClientSend(socket,oos)).start();
                new Thread(new ClientHeart(socket,oos)).start();
            }else {
                Connect.socketState=false;
                Connect.reConnnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            socketState=false;
            Connect.socketState=false;
            Connect.reConnnect();
        }
    }
    public static void reConnnect(){
        while (socketState!=true){
            System.out.print("断线重连中，请输入要连接的服务器ip地址");
            String str=new Scanner(System.in).next();
            getConnect(str,1234);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
